﻿using System;
using System.Collections.Generic;
using System.Configuration;

namespace MDCAdminTool.Configuration
{
	/// <summary>
	/// Configuration section for caching environment
	/// </summary>
	public class CachingConfiguration : ConfigurationSection
	{
		private const String SectionName = "CachingConfig";
		private const string ClustersPropertyName = "clusters";

		/// <summary>
		/// Reads current config information
		/// </summary>
		/// <returns></returns>
		public static CachingConfiguration Read()
		{
            CachingConfiguration section = null;

            try
            {
                section = ConfigurationManager.GetSection(SectionName) as CachingConfiguration;
            }
            catch (Exception)
            {                
            }

			if(section == null)
			{
				throw new ConfigurationErrorsException("Cannot load section " + SectionName);
			}

			return section;
		}

		/// <summary>
		/// Configuration placeholder for clusters elements
		/// </summary>
		[ConfigurationProperty(ClustersPropertyName)]
		public ClustersCollection Clusters
		{
			get
			{
				var clusters = this[ClustersPropertyName] as ClustersCollection;
				if(clusters == null)
				{
					throw new ConfigurationErrorsException(String.Format(@"Cannot read ""{0}"" property from config section ""{1}""",
					                                                     ClustersPropertyName, SectionName));
				}
				return (ClustersCollection) this[ClustersPropertyName];
			}
		}

		/// <summary>
		/// Retreives loaded <see cref="ClusterSettingElement"/> from config
		/// </summary>
		public IEnumerable<ClusterSettingElement> ClusterElements
		{
			get
			{
				var clustersCollection = Clusters;

				for (var i = 0; i < clustersCollection.Count; i++)
				{
					yield return clustersCollection[i];
				}
			}
		}
	}
}
